//
//  CYFinanceViewController.m
//  cyjf
//
//  Created by tauCross on 2017/5/3.
//  Copyright © 2017年 Auto Financing. All rights reserved.
//

#import "CYFinanceViewController.h"

#import "CYFinanceCell.h"
#import "CYFinanceTitleCell.h"
#import "CYEmptyCell.h"

#import "CYFinanceDetailViewController.h"
#import "CYFinanceSellOutViewController.h"

#import "CYDataAPIAdvertisementModel.h"

#import "CYActionManager.h"

#import <UIScrollView+TCRefresh.h>
#import <UIButton+WebCache.h>
#import <UIImage+GIF.h>
#import <YYAnimatedImageView.h>
#import <UIImageView+YYWebImage.h>



@interface CYFinanceViewController ()

@property(nonatomic, assign)BOOL loading;

@property(nonatomic, strong)UIButton *suspendButton;
@property(nonatomic, strong)YYAnimatedImageView *suspendImageView;
@property(nonatomic, strong)CYDataAPIAdvertisementModel *suspendModel;

@end



@implementation CYFinanceViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self loadDataFromServer];
}

- (void)loadUI
{
    self.navigationItem.title = @"理财";
    
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 10)];
    
    @weakify(self);
    [self.tableView setupRefreshWithBottomAt:0 refreshBlock:^{
        @strongify(self);
        [self loadDataFromServer];
    }];
    
    self.suspendButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 80, 80)];
    [self.suspendButton addTarget:self action:@selector(onSuspendButtonTouchUpInside) forControlEvents:UIControlEventTouchUpInside];
    [self.contentView addSubview:self.suspendButton];
    self.suspendImageView = [[YYAnimatedImageView alloc] init];
    [self.suspendButton addSubview:self.suspendImageView];
    [[TCRACObserve(self, suspendModel) takeUntil:self.rac_willDeallocSignal] subscribeNext:^(id x) {
        @strongify(self);
        if(self.suspendModel)
        {
            self.suspendButton.hidden = NO;
            [self.suspendImageView setYy_imageURL:self.suspendModel.image.tc_url];
        }
        else
        {
            self.suspendButton.hidden = YES;
        }
    }];
}

- (void)layoutUI
{
    self.tableView.frame = self.contentView.bounds;
    
    self.suspendButton.bottom = self.contentView.height - 100;
    self.suspendButton.right = self.contentView.width - 10;
    
    self.suspendImageView.frame = self.suspendButton.bounds;
}

- (void)loadSuspend
{
    @weakify(self);
    [CYStandardDataAPI advertisement_getListWithPosition:CYDataAPIAdvertisementPositionSuspend page_no:nil complete:^(CYResponse *response) {
        @strongify(self);
        if(response.code == 0)
        {
            if([response.content isKindOfClass:[NSArray class]] && [response.content count] && [[response.content firstObject] isKindOfClass:[NSDictionary class]])
            {
                self.suspendModel = [CYDataAPIAdvertisementModel mj_objectWithKeyValues:[response.content firstObject]];
                return;
            }
        }
        self.suspendModel = nil;
    }];
}

- (void)loadDataFromServer
{
    [self loadSuspend];
    if(self.loading)
    {
        return;
    }
    self.loading = YES;
    @weakify(self);
    [CYStandardDataAPI project_projectListWithComplete:^(CYResponse *response) {
        @strongify(self);
        if(response.code == 0)
        {
            NSMutableArray *cells = [NSMutableArray array];
            if([response.content isKindOfClass:[NSArray class]])
            {
                for(NSDictionary *category in response.content)
                {
                    if([category isKindOfClass:[NSDictionary class]])
                    {
                        NSArray *spList = category[@"spList"];
                        if([spList isKindOfClass:[NSArray class]] && [spList count] > 0)
                        {
                            CYFinanceTitleCellObject *titleCell = [CYFinanceTitleCellObject objectWithCellClass:[CYFinanceTitleCell class]];
                            titleCell.title = SAFE_STRING(category[@"categoryName"]);
                            titleCell.image = SAFE_STRING(category[@"categoryIcon"]);
                            if([category[@"categoryId"] isKindOfClass:[NSNumber class]] && [category[@"categoryId"] integerValue] == 10)
                            {
                                titleCell.type = CYFinanceTitleTypeSellOut;
                                titleCell.moreSellOutAction = ^{
                                    @strongify(self);
                                    [self moreSellOutAction];
                                };
                            }
                            else
                            {
                                titleCell.type = CYFinanceTitleTypeNormal;
                            }
                            [cells addObject:titleCell];
                            NSArray *models = [CYDataAPIFinanceModel mj_objectArrayWithKeyValuesArray:spList];
                            for(CYDataAPIFinanceModel *model in models)
                            {
                                CYFinanceCellObject *cell = [CYFinanceCellObject objectWithCellClass:[CYFinanceCell class]];
                                cell.model = [CYFinanceViewModel modelWithAPIModel:model];
                                [cells addObject:cell];
                                
                                CYEmptyCellObject *emptyCell = [CYEmptyCellObject objectWithCellClass:[CYEmptyCell class]];
                                emptyCell.height = 10;
                                [cells addObject:emptyCell];
                            }
                        }
                    }
                }
            }
            for(id cellObject in cells)
            {
                if([cellObject isKindOfClass:[CYFinanceCellObject class]])
                {
                    [(CYFinanceCellObject *)cellObject setReloadTableView:^{
                        @strongify(self);
                        [self.tableView reloadData];
                    }];
                }
            }
            self.tableModel = [[NIMutableTableViewModel alloc] initWithSectionedArray:cells delegate:(id)[NICellFactory class]];
            self.tableView.dataSource = self.tableModel;
            [self.tableView reloadData];
        }
        else
        {
            if([self.tableView isRefreshing])
            {
                [SVProgressHUD showErrorWithStatus:response.message];
            }
        }
        self.loading = NO;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            @strongify(self);
            [self.tableView endRefresh];
        });
    }];
}

- (void)onReceiveApplicationDidBecomeActiveNotification
{
    [self loadDataFromServer];
}

#pragma mark - Control Events
- (void)onSuspendButtonTouchUpInside
{
    if(self.suspendModel.action)
    {
        [CYStandardActionManager executeActionWithModel:self.suspendModel.action fromViewController:self];
    }
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    CYFinanceCellObject *cellObject = [self.tableModel objectAtIndexPath:indexPath];
    if([cellObject isKindOfClass:[CYFinanceCellObject class]])
    {
        [MobClick event:UM_EVENT_0021 label:cellObject.model.fid.stringValue];
        [self detailActionWithFid:cellObject.model.fid];
    }
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [UIView animateWithDuration:0.1 animations:^{
        self.suspendButton.alpha = 0.2;
    }];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if(decelerate == NO)
    {
        [UIView animateWithDuration:0.1 animations:^{
            self.suspendButton.alpha = 1;
        }];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    [UIView animateWithDuration:0.1 animations:^{
        self.suspendButton.alpha = 1;
    }];
}

#pragma mark - Actions
- (void)detailActionWithFid:(NSNumber *)fid
{
    CYFinanceDetailViewController *financeDetailViewController = [[CYFinanceDetailViewController alloc] init];
    financeDetailViewController.fid = fid;
    [self.navigationController pushViewController:financeDetailViewController animated:YES];
}

- (void)moreSellOutAction
{
    CYFinanceSellOutViewController *financeSellOutViewController = [[CYFinanceSellOutViewController alloc] init];
    [self.navigationController pushViewController:financeSellOutViewController animated:YES];
}

@end
